/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Represents a discussion post
 * 
 * 
 */
public class Post implements BotObject {
   /**
    * Removes the specified post
    * 
    * @param args
    *           specifies if the user is an admin, the post id and the name of the user who posted the post
    * @return true if the post is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 3)
		 return out;
	  PreparedStatement ps = null;
	  PreparedStatement ps2 = null;
	  ResultSet rs = null;
	  try {
		 boolean allowedToRemove = true;
		 if (Boolean.parseBoolean(args[0])) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM post WHERE id = ?");
			ps.setInt(1, Integer.parseInt(args[1]));
		 } else {
			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM post WHERE id = ?");
			ps.setInt(1, Integer.parseInt(args[1]));
			rs = ps.executeQuery();

			ps2 = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM " + "discussion WHERE id = ? AND private = false AND locked = false");
			ps2.setInt(1, rs.getInt("discussion"));
			rs = ps2.executeQuery();

			allowedToRemove = rs.next();

			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("DELETE FROM " + "post WHERE id = ? AND poster = ?");
			ps.setInt(1, Integer.parseInt(args[1]));
			ps.setString(2, args[2]);
		 }
		 if (allowedToRemove && ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps2.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Edits the specified post
    * 
    * @param postID
    *           the ID of the post to edit
    * @param sender
    *           who issued the edit command
    * @param editedMessage
    *           the new message
    * @param isAdmin
    *           admins can edit other users' posts
    * @return true if the post was successfully edited
    */
   public static boolean editPost(final int postID, final String sender, final String editedMessage, final boolean isAdmin) {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(sender) || StringTools.isNullOrEmpty(editedMessage))
		 return out;
	  PreparedStatement ps = null;
	  PreparedStatement ps2 = null;
	  ResultSet rs = null;
	  try {
		 boolean allowedToEdit = true;
		 if (isAdmin) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE post SET post = ? WHERE id = ?");
			ps.setString(1, editedMessage);
			ps.setInt(2, postID);
		 } else {
			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM post WHERE id = ?");
			ps.setInt(1, postID);
			rs = ps.executeQuery();

			if (rs.next()) {
			   ps2 = DBConnectionFactory.getConnectionHandler().getConnection()
					 .prepareStatement("SELECT * FROM " + "discussion WHERE id = ? AND private = false AND locked = false");
			   ps2.setInt(1, rs.getInt("discussion"));
			   rs = ps2.executeQuery();

			   allowedToEdit = rs.next();

			   try {
				  ps.close();
			   } catch (final Exception e) {
			   }

			   ps = DBConnectionFactory.getConnectionHandler().getConnection()
					 .prepareStatement("UPDATE post SET " + "post = ? WHERE id = ? AND poster = ?");
			   ps.setString(1, editedMessage);
			   ps.setInt(2, postID);
			   ps.setString(3, sender);
			}
		 }
		 if (allowedToEdit && ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps2.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all the posts from the specified discussion
    * 
    * @param discussionID
    *           The ID of the discussion
    * @param isAdmin
    *           Decides whether the discussion is accessible to this user
    * @return a List of Post objects
    */
   public static List<Post> getPosts(final int discussionID, final boolean isAdmin) {
	  List<Post> out = new LinkedList<Post>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 boolean allowedToRead = true;
		 if (!isAdmin) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM " + "discussion WHERE id = ? AND private = false");
			ps.setInt(1, discussionID);
			rs = ps.executeQuery();

			allowedToRead = rs.next();
		 }
		 if (allowedToRead) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM " + "post WHERE discussion = ? ORDER BY posted");
			ps.setInt(1, discussionID);
			rs = ps.executeQuery();
			while (rs.next()) {
			   out.add(new Post(rs.getInt("id"), rs.getString("post"), rs.getString("poster"), rs.getTimestamp("posted")
					 .getTime(), rs.getInt("discussion"), allowedToRead));
			}
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private int id = 0;
   private String post = "";
   private String poster = "";

   private Long posted = 0L;

   private int discussionID = 0;

   private boolean posterIsAdmin = false;

   public Post(final int id, final String post, final String poster, final Long posted, final int discussionID,
		 final boolean posterIsAdmin) {
	  this.id = id;
	  this.post = post;
	  this.poster = poster;
	  this.posted = posted;
	  this.discussionID = discussionID;
	  this.posterIsAdmin = posterIsAdmin;
   }

   public int getDiscussionID() {
	  return discussionID;
   }

   public int getId() {
	  return id;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (args.length < 1 || StringTools.isNullOrEmpty(getPoster()) || StringTools.isNullOrEmpty(getPost())
			|| getPosted() == null)
		 return out;
	  String pattern = "EEE, MMM d, H:mm:ss";
	  SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
	  TimeZone tz = TimeZone.getTimeZone("GMT" + args[0]);
	  sdf.setTimeZone(tz);
	  Date irlTime = new Date(getPosted());
	  out.add(Colors.OLIVE + "ID: " + Colors.BLUE + getId() + " " + Colors.OLIVE + "Posted by: " + Colors.BLUE + getPoster()
			+ Colors.OLIVE + " Added: " + Colors.BLUE + sdf.format(irlTime));
	  out.add(Colors.NORMAL + getPost());
	  return out;
   }

   public String getPost() {
	  return post;
   }

   public Long getPosted() {
	  return posted;
   }

   public String getPoster() {
	  return poster;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getPoster()) || StringTools.isNullOrEmpty(getPost()) || getPosted() == null)
		 return out;
	  out.put("ID", getId());
	  out.put("Post", getPost());
	  out.put("Poster", getPoster());
	  out.put("Posted Time", new Date(getPosted()));
	  out.put("Discussion ID", getDiscussionID());
	  out.put("Poster is Admin", posterIsAdmin());
	  return out;
   }

   public boolean posterIsAdmin() {
	  return posterIsAdmin;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getPoster()) || StringTools.isNullOrEmpty(getPost()) || getPosted() == null)
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 boolean allowedToPost = true;
		 if (!posterIsAdmin()) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM discussion " + "WHERE id = ? AND private = false AND locked = false");
			ps.setInt(1, discussionID);
			rs = ps.executeQuery();

			allowedToPost = rs.next();
		 }
		 if (allowedToPost) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("INSERT INTO post VALUES(default,?,?,?,?)");
			ps.setInt(1, getDiscussionID());
			ps.setString(2, getPoster());
			ps.setString(3, getPost());
			ps.setTimestamp(4, new Timestamp(getPosted()));
			if (ps.executeUpdate() == 1) {
			   out = true;
			}
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }
}
